<?php

declare(strict_types=1);

namespace app\shop\controller\admin\goods;

use app\shop\controller\traits\SkuPrice as SkuPriceTrait;
use app\shop\model\activity\Activity as ActivityModel;
use app\shop\model\goods\Goods as GoodsModel;
use app\shop\model\goods\Sku as SkuModel;
use app\shop\model\goods\SkuPrice as SkuPriceModel;
use app\shop\model\goods\StockWarning as StockWarningModel;
use app\shop\service\goods\GoodsService;
use app\shop\traits\StockWarning as StockWarningTrait;
use login\Demo;
use sheep\controller\Backend;
use think\facade\Db;
use think\Request;

class Goods extends Backend
{
    use SkuPriceTrait, StockWarningTrait;

    public function initialize()
    {
        $this->model = new GoodsModel;
        $this->activityModel = new ActivityModel;
    }

    /**
     * 商品列表
     *
     * @return \think\Response
     */
    public function list()
    {

        $goodsTableName = $this->model->db()->getTable();

        $goods = $this->model->where('source_type','mall')->sheepFilter()->with(['max_sku_price']);

        // 聚合库存 (包含下架的规格)
        $skuSql = SkuPriceModel::field('sum(stock) as stock, goods_id as sku_goods_id')->group('goods_id')->buildSql();
        $goods = $goods->join([$skuSql => 'sp'], $goodsTableName . '.id = sp.sku_goods_id', 'left')
            ->field("$goodsTableName.*, sp.stock")       // ,score.*
            ->paginate(request()->param('list_rows', 10))->each(function($goods) {
                // 获取活动信息
                $goods->activities = $goods->activities;
                $goods->promos = $goods->promos;

                $data_type = request()->param('data_type', '');       // 特殊 type 需要处理的数据
                if ($data_type == 'score_shop') {
                    $goods->is_score_shop = $goods->is_score_shop;
                }
            });

        return success('获取成功', $goods);
    }


    // 获取数据类型
    public function getType()
    {
        $activityTypes = (new \app\shop\model\activity\Activity)->typeList();
        $statusList = $this->model->statusList();

        $result = [
            'activity_type' => $activityTypes,
            'status' => $statusList
        ];

        $data = [];
        foreach ($result as $key => $list) {
            $data[$key][] = ['name' => '全部', 'type' => 'all'];

            foreach ($list as $k => $v) {
                $data[$key][] = [
                    'name' => $v,
                    'type' => $k
                ];
            }
        }

        return success('获取成功', $data);
    }




    /**
     * 添加商品
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {

        $params = $this->request->only([
            'type', 'title', 'subtitle', 'category_ids', 'image', 'image_wh', 'images', 'params',
            'original_price', 'price', 'is_sku', 'limit_type', 'limit_num', 'sales_show_type',
            'stock_show_type', 'show_sales', 'service_ids', 'dispatch_type', 'dispatch_id', 'is_offline', 'status', 'weigh',
        ]);         // likes, views, sales,
        $params['content'] = $request->param('content', '', null);      // content 不经过全局过滤
        $organ_id = $this->auth()->user()->organ_id;
        $store_id = Db::name('shop_store')->where('organ_id', $organ_id)->find();
        $params['store_id'] = $store_id['id'] ?? null;
        $this->svalidate($params, ".add");
        $sku_params = [];
        if (!$params['is_sku']) {
            // 校验单规格属性
            $sku_params = $this->request->only(['stock', 'stock_warning', 'sn', 'weight', 'cost_price', 'original_price', 'price']);
            $this->svalidate($sku_params, '.sku_params');
        }

        $data = Db::transaction(function () use ($params) {
            $this->model->save($params);

            $this->editSku($this->model, 'add');
        });
//        $Authorization = Demo::login();
//        // 同步到萌宠霸王
//
//        $result = Demo::sendGoods(array_merge($params, $sku_params), $Authorization);
        return success('保存成功', $data);
    }


    public function send($params){

    }


    /**
     * 商品详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $goods = $this->model->findOrFail($id);

        $goods->category_ids_arr = $goods->category_ids_arr;

        if ($goods->is_sku) {
            $goods->skus = $goods->skus;
            $goods->sku_prices = $goods->sku_prices;
        } else {
            // 将单规格的部分数据直接放到 row 上
            $goodsSkuPrice = SkuPriceModel::where('goods_id', $id)->order('id', 'asc')->find();

            $goods->stock = $goodsSkuPrice->stock;
            $goods->sn = $goodsSkuPrice->sn;
            $goods->weight = $goodsSkuPrice->weight;
            $goods->stock_warning = $goodsSkuPrice->stock_warning;
            $goods->cost_price = $goodsSkuPrice->cost_price;
        }

        $content = $goods['content'];
        $goods = $goods->toArray();
        $goods['content'] = $content;
        return success('获取成功', $goods);
    }



    /**
     * 商品编辑
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        $params = $this->request->only([
            'type', 'title', 'subtitle', 'image', 'images', 'image_wh', 'params',
            'original_price', 'price', 'is_sku', 'limit_type', 'limit_num', 'sales_show_type',
            'stock_show_type', 'show_sales', 'service_ids', 'dispatch_type', 'dispatch_id', 'is_offline', 'status', 'weigh',
        ]);         // likes, views, sales,
        $request->has('content') && $params['content'] = $request->param('content', '', null);      // content 不经过全局过滤
        $this->svalidate($params);
        isset($params['is_sku']) && $params['category_ids'] = $this->request->param('category_ids', '');        // 分类不判空
        $sku_params = [];
        if (isset($params['is_sku']) && !$params['is_sku']) {
            // 校验单规格属性
            $sku_params = $this->request->only(['stock_warning', 'sn', 'weight', 'cost_price', 'original_price', 'price']);
            $this->svalidate($sku_params, 'sku_params');
        }

        $id = explode(',', $id);
        $organ_id = $this->auth()->user()->organ_id;
        $store_id = Db::name('shop_store')->where('organ_id', $organ_id)->find();
        $params['store_id'] = $store_id['id'] ?? null;
        Db::transaction(function () use ($id, $params) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $goods) {
                $goods->save($params);

                if (isset($params['is_sku'])) {
                    // 编辑商品（如果没有 is_sku 就是批量编辑上下架等）
                    $this->editSku($goods, 'edit');
                }
            }
        });
//        $Authorization = Demo::login();
//        // 同步到萌宠霸王
//
//        $result = Demo::saveGoods(array_merge($params, $sku_params), $Authorization);
        return success('更新成功');
    }


    public function addStock(Request $request, $id) 
    {
        $goods = $this->model->findOrFail($id);

        if ($goods->is_sku) {
            // 多规格
            $skuPrices = $request->param('sku_prices', []);
            foreach ($skuPrices as $skuPrice) {
                if (isset($skuPrice['add_stock']) && $skuPrice['add_stock'] != 0 && $skuPrice['id']) {
                    $skuPriceModel = SkuPriceModel::where('goods_id', $id)->order('id', 'asc')->find($skuPrice['id']);
                    if ($skuPriceModel) {
                        Db::transaction(function () use ($skuPriceModel, $skuPrice) {
                            $this->addStockToSkuPrice($skuPriceModel, $skuPrice['add_stock'], 'goods');
                        });
                    }
                }
            }
        } else {
            $add_stock = $request->param('add_stock', 0);
            $skuPriceModel = SkuPriceModel::where('goods_id', $id)->order('id', 'asc')->find();

            if ($skuPriceModel) {
                Db::transaction(function () use ($skuPriceModel, $add_stock) {
                    $this->addStockToSkuPrice($skuPriceModel, $add_stock, 'goods');
                });
            }
        }

        return success('补货成功');
    }


    public function select(Request $request)
    {
        $type = $request->param('type', 'page');
        $goodsTableName = $this->model->db()->getTable();

        $goods = $this->model->sheepFilter()->with(['max_sku_price']);

        // 聚合库存 (包含下架的规格)
        $skuSql = SkuPriceModel::field('sum(stock) as stock, goods_id as sku_goods_id')->group('goods_id')->buildSql();
        $goods = $goods->join([$skuSql => 'sp'], $goodsTableName . '.id = sp.sku_goods_id', 'left')
            ->field("$goodsTableName.*, sp.stock");       // ,score.*

        if ($type == 'select') {
            // 普通结果
            $goods = $goods->select();
        } else {
            // 分页结果
            $goods = $goods->paginate(request()->param('list_rows', 10));
        }
        
        $goods = $goods->each(function ($goods) {
            // 获取活动信息
            $goods->activities = $goods->activities;
            $goods->promos = $goods->promos;

            $data_type = request()->param('data_type', '');       // 特殊 type 需要处理的数据
            if ($data_type == 'score_shop') {
                $goods->is_score_shop = $goods->is_score_shop;
            }
        });

        return success('获取成功', $goods);
    }



    /**
     * 获取指定活动相关商品
     *
     * @param Request $request
     * @return void
     */
    public function activitySelect(Request $request)
    {
        $activity_id = $request->param('activity_id');
        $need_buyers = $request->param('need_buyers', 0);      // 需要查询哪些人在参与活动
        $activity = $this->activityModel->findOrFail($activity_id);
        $goodsIds = $activity->goods_ids ? explode(',', $activity->goods_ids) : [];

        // 存一下，获取器获取指定活动的时候会用到
        foreach($goodsIds as $id) {
            session('goods-activity_id:' . $id, $activity_id);
        }
        $service = new GoodsService(function ($goods) use ($need_buyers) {
            if ($need_buyers) {
                $goods->buyers = $goods->buyers;
            }
            $goods->activity = $goods->activity;
            return $goods;
        });

        $goods = $service->activity($activity_id)->whereIds($goodsIds)->show()->select()->toArray();
        foreach ($goods as &$gd) {
            unset($gd['new_sku_prices'], $gd['activity']);
        }
        return success('获取成功', $goods);
    }



    /**
     * 删除商品
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        Db::transaction(function () use ($id) {
            foreach ($this->model->whereIn('id', $id)->cursor() as $goods) {
                // 删除相关库存预警记录
                StockWarningModel::destroy(function ($query) use ($goods) {
                    $query->where('goods_id', $goods->id);
                });
                $goods->delete();
            }
        });

        return success('删除成功');
    }


    public function recyclebin() 
    {
        $goods = $this->model->onlyTrashed()->sheepFilter()->paginate(request()->param('list_rows', 10));

        return success('获取成功', $goods);
    }


    /**
     * 还原(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function restore($id)
    {

        Db::transaction(function () use ($id) {
            foreach ($this->model->onlyTrashed()->whereIn('id', $id)->cursor() as $goods) {
                $goods->restore();
            }
        });

        return success('还原成功');
    }


    /**
     * 销毁(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function destroy($id)
    {
        $result = Db::transaction(function () use ($id) {
            $count = 0;
            if ($id !== 'all') {
                $model = $this->model->onlyTrashed()->whereIn('id', $id);
            } else {
                $model = $this->model->onlyTrashed();
            }

            foreach ($model->cursor() as $goods) {
                // 删除商品相关的规格，规格记录
                SkuModel::where('goods_id', $goods->id)->delete();
                SkuPriceModel::where('goods_id', $goods->id)->delete();

                // 删除商品
                $count += $goods->force()->delete();
            }
            return $count;
        });

        if ($result) {
            return success('销毁成功', $result);
        }
        return error('销毁失败');
    }
}
